import numpy as np
import h5py
import glob
import os

def merge_data():
    # 输入和输出目录设置
    input_dir = r'E:\MLdata\AFFon\cali_data'
    output_file = os.path.join(input_dir, 'merged_data.h5')
    
    # 获取所有校准数据文件
    h5_files = glob.glob(os.path.join(input_dir, '*_cali.h5'))
    if not h5_files:
        print("错误：未找到校准数据文件")
        return
    
    print(f"找到 {len(h5_files)} 个校准数据文件")
    
    # 用于存储所有数据的列表
    all_data = {
        'Vc_real': [], 'Vc_imag': [],
        'Vf_real': [], 'Vf_imag': [],
        'Vr_real': [], 'Vr_imag': [],
        'a_real': [], 'a_imag': []
    }
    
    # 读取所有文件的数据
    for file_path in h5_files:
        print(f"\n处理文件: {os.path.basename(file_path)}")
        try:
            with h5py.File(file_path, 'r') as f:
                # 遍历所有索引组
                for group_name in f.keys():
                    group = f[group_name]
                    
                    # 读取并存储所有数据
                    for key in all_data.keys():
                        data = group[key][()]
                        if isinstance(data, np.ndarray):
                            all_data[key].extend(data.flatten())
                        else:
                            all_data[key].append(data)
                            
                print(f"已读取 {len(f.keys())} 个索引组的数据")
                
        except Exception as e:
            print(f"处理文件 {file_path} 时出错: {str(e)}")
            continue
    
    # 将所有数据转换为numpy数组
    for key in all_data:
        all_data[key] = np.array(all_data[key])
        print(f"{key}: {len(all_data[key])} 个数据点")
    
    # 保存合并后的数据
    print(f"\n保存合并数据到: {output_file}")
    with h5py.File(output_file, 'w') as f:
        # 创建数据集
        for key, value in all_data.items():
            f.create_dataset(key, data=value)
    
    print("数据合并完成！")

if __name__ == '__main__':
    merge_data() 